/**
 * 
 */
package edu.unr.cater.npap.client.scaffold;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import edu.unr.cater.npap.client.AuthService;
import edu.unr.cater.npap.client.AuthServiceAsync;
import edu.unr.cater.npap.client.scaffold.ioc.DesktopInjectorWrapper;
import edu.unr.cater.npap.client.scaffold.ioc.InjectorWrapper;
import edu.unr.cater.npap.client.scaffold.ui.LoginWidget;

/**
 * @author Hao
 * 
 */
public class CustomizedDesktopLoginShell extends Composite implements HasText {

	final private InjectorWrapper injectorWrapper = GWT
			.create(DesktopInjectorWrapper.class);
	private ScaffoldDesktopShell mainShell;

	private static CustomizedDesktopLoginShellUiBinder uiBinder = GWT
			.create(CustomizedDesktopLoginShellUiBinder.class);

	interface CustomizedDesktopLoginShellUiBinder extends
			UiBinder<Widget, CustomizedDesktopLoginShell> {
	}

	/**
	 * Because this class has a default constructor, it can be used as a binder
	 * template. In other words, it can be used in other *.ui.xml files as
	 * follows: <ui:UiBinder xmlns:ui="urn:ui:com.google.gwt.uibinder"
	 * xmlns:g="urn:import:**user's package**">
	 * <g:**UserClassName**>Hello!</g:**UserClassName> </ui:UiBinder> Note that
	 * depending on the widget that is used, it may be necessary to implement
	 * HasHTML instead of HasText.
	 */
	public CustomizedDesktopLoginShell() {
		initWidget(uiBinder.createAndBindUi(this));
		loginWidget.setLogoutUrl("/j_spring_security_logout");
	}

	@UiField
	public TextBox loginBox;

	@UiField
	public TextBox passwordBox;

	@UiField
	Label completionLabel1;

	@UiField
	Label completionLabel2;

	private Boolean tooShort = false;
	@UiField
	Button button;

	@UiField
	LoginWidget loginWidget;

	public CustomizedDesktopLoginShell(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));

		// Can access @UiField after calling createAndBindUi

		button.setText(firstName);
		loginWidget.setLogoutUrl("/j_spring_security_logout");
	}

	@UiHandler("buttonSubmit")
	void doClickSubmit(ClickEvent event) {
		AuthServiceAsync authService = GWT.create(AuthService.class);

		// authService.retrieveUsername(new AsyncCallback<String>() {
		// public void onFailure(Throwable caught) {
		// Window.alert("Remote Procedure Call - Failure");
		// }
		//
		// public void onSuccess(String result) {
		// Window.alert(result);
		// }
		// });
		authService.logIn(loginBox.getText(), passwordBox.getText(),
				new AsyncCallback<Boolean>() {

					@Override
					public void onSuccess(Boolean result) {
						// TODO Auto-generated method stub
						if (result)
							reloadMainPage();
						// Window.Location.reload();
						else
							Window.alert("Username and passord do not match!");
					}

					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert("Remote Procedure Call - Failure");

					}
				});

		// if (tooShort) {
		// Window.alert("Login Successful!");
		// } else {
		// Window.alert("Login or Password is too short!");
		// }
	}

	@UiHandler("loginBox")
	void handleLoginChange(ValueChangeEvent<String> event) {
		if (event.getValue().length() < 6) {
//			completionLabel1.setText("Login too short (Size must be > 6)");
			tooShort = true;
		} else {
			tooShort = false;
			completionLabel1.setText("");
		}
	}

	@UiHandler("passwordBox")
	void handlePasswordChange(ValueChangeEvent<String> event) {
		if (event.getValue().length() < 6) {
			tooShort = true;
//			completionLabel2.setText("Password too short (Size must be > 6)");
		} else {
			tooShort = false;
			completionLabel2.setText("");
		}
	}

	@UiHandler("button")
	void onClick(ClickEvent e) {
		Window.alert("Hello!");
	}

	public void setText(String text) {
		button.setText(text);
	}

	/**
	 * Gets invoked when the default constructor is called and a string is
	 * provided in the ui.xml file.
	 */
	public String getText() {
		return button.getText();
	}

	/**
	 * Added by Hao, Refresh the page when the login is successful
	 */
	private void reloadMainPage() {
		if(this.mainShell==null)
		{
			Window.alert("There is no main shell object, the code needs to be checked.");
		}else
		{
			RootLayoutPanel.get().clear();
			RootLayoutPanel.get().add(this.mainShell);
			this.mainShell.loginWidget.setUserName(loginBox.getText());
			this.mainShell.loginWidget.setLogoutUrl("/j_spring_security_logout");
		}
	}
	
	public void setMainShell(ScaffoldDesktopShell shell){
		this.mainShell=shell;
	}

}
